package com.daily.DailyStudy.接口.后端接口.controller;

import com.daily.DailyStudy.接口.后端接口.model.User;
import com.daily.DailyStudy.接口.后端接口.ExceptionHandle.APIException;
import com.daily.DailyStudy.接口.后端接口.自定义统一响应体.ResultVO;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
/**
 * 参考url：https://zhuanlan.zhihu.com/p/245405288
 * 报文如下：
  {
      "account": "12345678",
      "email": "123@qq.com",
      "id": 0,

 '?'
      "password": "1231"
  }
 *
 * */
@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("/addUser")
    public String addUser(@RequestBody @Valid User user, BindingResult bindingResult){
        System.out.println("user:"+user);
        // 如果有参数校验失败，会将错误信息封装成对象组装在BindingResult里
        for(ObjectError error : bindingResult.getAllErrors()){
            System.out.println("错误: "+error.getDefaultMessage());
            return error.getDefaultMessage();
        }
        return "/addUser";
    }

    @RequestMapping("/addUser02")
    public String addUser02(@RequestBody @Valid User user) {
        System.out.println("user:"+user);
        return "/addUser";
    }
    /**
     * error自定义异常处理
     * */
    @RequestMapping("/addUser03")
    public String addUser03(@RequestBody @Valid User user) {
        if(true){
            throw new APIException();
        }
        return "/addUser";
    }
    /**
     * success
     * */
    @RequestMapping("/getUser")
    public ResultVO getUser() {
        User user = new User();
        user.setId(1L);
        user.setAccount("12345678");
        user.setPassword("12345678");
        user.setEmail("123@qq.com");

        return new ResultVO<>(user);
    }

    /**
     * 空指针异常
     * */
    @RequestMapping("/nullDemo")
    public ResultVO nullDemo() {
        String demo = null;
        demo.length();

        User user = new User();
        user.setId(1L);
        user.setAccount("12345678");
        user.setPassword("12345678");
        user.setEmail("123@qq.com");
        return new ResultVO<>(user);
    }

}
